import { useState, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Download, Upload, FileJson, AlertCircle, CheckCircle, X } from 'lucide-react';

interface SubAgentImportExportProps {
  onClose: () => void;
}

interface ImportResult {
  success: number;
  failed: number;
  skipped: number;
  errors: string[];
}

export function SubAgentImportExport({ onClose }: SubAgentImportExportProps) {
  const [mode, setMode] = useState<'select' | 'import' | 'export'>('select');
  const [importing, setImporting] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [importData, setImportData] = useState<any[]>([]);
  const [overwriteExisting, setOverwriteExisting] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleExport = async () => {
    setExporting(true);

    try {
      const response = await fetch('http://localhost:3000/api/subagents/export');
      const data = await response.json();

      if (data.success) {
        // Create a blob and download
        const blob = new Blob([JSON.stringify(data.data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `subagents-export-${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        setMode('select');
      }
    } catch (error) {
      console.error('Failed to export sub-agents:', error);
    } finally {
      setExporting(false);
    }
  };

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const json = JSON.parse(e.target?.result as string);
        if (Array.isArray(json)) {
          setImportData(json);
          setMode('import');
        } else {
          alert('Invalid file format. Expected an array of sub-agents.');
        }
      } catch (error) {
        alert('Failed to parse JSON file.');
      }
    };
    reader.readAsText(file);
  };

  const handleImport = async () => {
    setImporting(true);
    setImportResult(null);

    try {
      const response = await fetch('http://localhost:3000/api/subagents/import', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          subagents: importData,
          overwrite: overwriteExisting,
        }),
      });

      const data = await response.json();

      if (data.success) {
        setImportResult(data.data);
      } else {
        setImportResult({
          success: 0,
          failed: importData.length,
          skipped: 0,
          errors: [data.error?.message || 'Import failed'],
        });
      }
    } catch (error) {
      setImportResult({
        success: 0,
        failed: importData.length,
        skipped: 0,
        errors: ['Network error: ' + error],
      });
    } finally {
      setImporting(false);
    }
  };

  const handleReset = () => {
    setMode('select');
    setImportData([]);
    setImportResult(null);
    setOverwriteExisting(false);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b px-6 py-4 flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold">Import / Export Sub-Agents</h2>
          <p className="text-sm text-muted-foreground mt-1">
            Backup or restore your sub-agent configurations
          </p>
        </div>
        <Button variant="ghost" onClick={onClose}>
          <X className="w-4 h-4 mr-2" />
          Close
        </Button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-6">
        {mode === 'select' && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-4xl mx-auto">
            {/* Export Card */}
            <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setMode('export')}>
              <CardHeader>
                <div className="flex items-center gap-3">
                  <div className="p-3 bg-blue-100 rounded-lg">
                    <Download className="w-6 h-6 text-blue-600" />
                  </div>
                  <div>
                    <CardTitle>Export</CardTitle>
                    <CardDescription>Download sub-agents as JSON</CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  Export all your custom sub-agents to a JSON file for backup or sharing.
                </p>
              </CardContent>
            </Card>

            {/* Import Card */}
            <Card className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => fileInputRef.current?.click()}>
              <CardHeader>
                <div className="flex items-center gap-3">
                  <div className="p-3 bg-green-100 rounded-lg">
                    <Upload className="w-6 h-6 text-green-600" />
                  </div>
                  <div>
                    <CardTitle>Import</CardTitle>
                    <CardDescription>Upload sub-agents from JSON</CardDescription>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground">
                  Import sub-agents from a previously exported JSON file.
                </p>
              </CardContent>
            </Card>

            <input
              ref={fileInputRef}
              type="file"
              accept=".json"
              onChange={handleFileSelect}
              className="hidden"
            />
          </div>
        )}

        {mode === 'export' && (
          <Card className="max-w-2xl mx-auto">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Download className="w-5 h-5" />
                Export Sub-Agents
              </CardTitle>
              <CardDescription>
                Download all your custom sub-agents as a JSON file
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="bg-blue-50 border border-blue-200 rounded-md p-4">
                <h4 className="font-semibold text-sm mb-2">📦 What will be exported:</h4>
                <ul className="text-sm space-y-1 text-muted-foreground">
                  <li>• All custom sub-agents (builtin sub-agents are excluded)</li>
                  <li>• Complete configuration including prompts, tools, and settings</li>
                  <li>• Metadata and tags</li>
                </ul>
              </div>

              <div className="flex gap-2">
                <Button variant="outline" onClick={handleReset} className="flex-1">
                  Cancel
                </Button>
                <Button onClick={handleExport} disabled={exporting} className="flex-1">
                  {exporting ? (
                    <>
                      <Download className="w-4 h-4 mr-2 animate-bounce" />
                      Exporting...
                    </>
                  ) : (
                    <>
                      <Download className="w-4 h-4 mr-2" />
                      Export Now
                    </>
                  )}
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {mode === 'import' && !importResult && (
          <Card className="max-w-2xl mx-auto">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Upload className="w-5 h-5" />
                Import Sub-Agents
              </CardTitle>
              <CardDescription>
                Review and import sub-agents from the selected file
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="bg-green-50 border border-green-200 rounded-md p-4">
                <div className="flex items-start gap-2">
                  <FileJson className="w-5 h-5 text-green-600 mt-0.5" />
                  <div>
                    <h4 className="font-semibold text-sm mb-1">File loaded successfully</h4>
                    <p className="text-sm text-muted-foreground">
                      Found {importData.length} sub-agent{importData.length !== 1 ? 's' : ''} in the file
                    </p>
                  </div>
                </div>
              </div>

              <div className="space-y-2">
                <h4 className="font-semibold text-sm">Sub-agents to import:</h4>
                <div className="max-h-60 overflow-y-auto space-y-2">
                  {importData.map((agent, index) => (
                    <div key={index} className="flex items-center justify-between p-3 bg-muted rounded-md">
                      <div>
                        <div className="font-medium text-sm">{agent.name}</div>
                        <div className="text-xs text-muted-foreground">{agent.description?.slice(0, 60)}...</div>
                      </div>
                      <Badge variant="secondary">{agent.category || 'uncategorized'}</Badge>
                    </div>
                  ))}
                </div>
              </div>

              <div className="flex items-center gap-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
                <input
                  type="checkbox"
                  id="overwrite"
                  checked={overwriteExisting}
                  onChange={(e) => setOverwriteExisting(e.target.checked)}
                  className="w-4 h-4"
                />
                <label htmlFor="overwrite" className="text-sm cursor-pointer">
                  Overwrite existing sub-agents with the same ID
                </label>
              </div>

              <div className="flex gap-2">
                <Button variant="outline" onClick={handleReset} className="flex-1">
                  Cancel
                </Button>
                <Button onClick={handleImport} disabled={importing} className="flex-1">
                  {importing ? (
                    <>
                      <Upload className="w-4 h-4 mr-2 animate-bounce" />
                      Importing...
                    </>
                  ) : (
                    <>
                      <Upload className="w-4 h-4 mr-2" />
                      Import {importData.length} Sub-Agent{importData.length !== 1 ? 's' : ''}
                    </>
                  )}
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {mode === 'import' && importResult && (
          <Card className="max-w-2xl mx-auto">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                {importResult.failed === 0 ? (
                  <CheckCircle className="w-5 h-5 text-green-600" />
                ) : (
                  <AlertCircle className="w-5 h-5 text-yellow-600" />
                )}
                Import Complete
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-3 gap-4">
                <div className="text-center p-4 bg-green-50 rounded-md">
                  <div className="text-2xl font-bold text-green-600">{importResult.success}</div>
                  <div className="text-sm text-muted-foreground">Imported</div>
                </div>
                <div className="text-center p-4 bg-yellow-50 rounded-md">
                  <div className="text-2xl font-bold text-yellow-600">{importResult.skipped}</div>
                  <div className="text-sm text-muted-foreground">Skipped</div>
                </div>
                <div className="text-center p-4 bg-red-50 rounded-md">
                  <div className="text-2xl font-bold text-red-600">{importResult.failed}</div>
                  <div className="text-sm text-muted-foreground">Failed</div>
                </div>
              </div>

              {importResult.errors.length > 0 && (
                <div className="bg-red-50 border border-red-200 rounded-md p-4">
                  <h4 className="font-semibold text-sm mb-2 text-red-800">Errors:</h4>
                  <ul className="text-sm space-y-1 text-red-700">
                    {importResult.errors.map((error, index) => (
                      <li key={index}>• {error}</li>
                    ))}
                  </ul>
                </div>
              )}

              <Button onClick={handleReset} className="w-full">
                Done
              </Button>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}

